# -*- coding: utf-8 -*-

import logging

from odoo import fields, models, api, _
from odoo.exceptions import UserError, ValidationError

_logger = logging.getLogger(__name__)


class StockMove(models.Model):
    _inherit = 'stock.move'

    supplier_lot_name = fields.Char('supplier lot')
    production_date = fields.Date(string="Production date")
    warranty_date = fields.Date(string="Warranty date")
    product_code = fields.Char(related="product_id.default_code", string="Material code")
    must_stock_field_tag = fields.Boolean(string='Must Stock Field Tag',
                                          related="product_id.product_tmpl_id.categ_id.must_stock_field_tag")
    s_actual_quantity = fields.Float(string='quantity available', related='product_id.s_actual_quantity')
    s_delivery_date = fields.Date(string="Delivery date", compute='_compute_delivery_date', store=True)
    s_report_not_counted = fields.Boolean('Not counted', default=False, copy=False, readonly=True)

    @api.depends('product_id')
    def _compute_delivery_date(self):
        for record in self:
            # 获取请购单需求日期
            requisition_date = record.purchase_line_id.pr_line_id.requirement_date
            record.s_delivery_date = requisition_date

    @api.constrains('reference')
    def _constraint_reference(self):
        for record in self:
            if record.picking_type_id.barcode == 'WTT-RECEIPTS':
                record.move_line_ids.update({'quantity': 0})

    # @api.constrains('state')
    # def _s_check_supplier_lot_name(self):
    #     for record in self.filtered(lambda x:x.state == 'done' \
    #             and  x.location_id == self.env.ref('stock.stock_location_suppliers') \
    #             and x.location_dest_id == self.env.ref('stock.stock_location_stock')):
    #         if record.must_stock_field_tag and record.quantity > 0 and (not record.supplier_lot_name or not record.production_date):
    #             raise ValidationError(_("Type: {product_categ_name} Relevant products are marked as required when the processing quantity is valid. Fields: Supplier Batch and Production Date").format(product_categ_name = record.product_id.categ_id.name))

    # def _prepare_move_line_vals(self, quantity=None, reserved_quant=None):
    #     vals = super(StockMove, self)._prepare_move_line_vals(quantity=quantity, reserved_quant=reserved_quant)
    #     seq_rec = self.env['ir.sequence'].sudo().search([('code', '=', 'stock.lot.serial')], limit=1)
    #     if seq_rec:
    #         vals.update({
    #             'lot_name': seq_rec._next()
    #         })
    #     return vals

    # def _action_done(self, cancel_backorder=False):
    #     result = super()._action_done(cancel_backorder=cancel_backorder)
    #     for move in result:
    #         if move.location_id.usage == 'supplier':
    #             move.mapped('lot_ids').update({
    #                 'production_date': move.production_date,
    #                 'supplier_lot_name': move.supplier_lot_name
    #             })
    #     return result

    @api.onchange('lot_ids')
    def _onchange_lot_ids_single(self):
        for record in self:
            for lot in record.lot_ids:
                # 价格是否一致,如果不一致不允许使用旧批次, 仅检查采购单, 其他订单不检查, [采购入库,采购退货]
                purchase_line = record.purchase_line_id
                if not purchase_line:
                    continue
                lot_ids = self.env['stock.lot'].sudo().search([('id', 'in', lot.ids)])
                old_purchase = lot_ids.purchase_order_ids
                if not old_purchase:
                    continue
                order_line = old_purchase.order_line.filtered(lambda x: x.product_id.id == record.product_id.id)
                if not order_line:
                    continue
                ol = order_line[0]
                if ol.price_unit != purchase_line.price_unit:
                    raise ValidationError(_("Existing Serial numbers. Please correct the serial numbers encoded."))
                # 判断同一批次采购入库单是否一致
                order = purchase_line.order_id
                if order.id not in old_purchase.ids:
                    raise ValidationError(_("Existing Serial numbers. Please correct the serial numbers encoded."))

    def _action_done(self, cancel_backorder=False):
        res = super()._action_done(cancel_backorder)
        for move in self.filtered(lambda x: x.state == 'done'):
            # 产品移动的产品和库存移动的产品不同，报错
            if move.move_line_ids.filtered(lambda x: x.product_id != move.product_id):
                raise ValidationError(_('move and move line product different，Please check'))

        return res